package cn.yr.common.oss;


import com.UpYun;
import com.upyun.UpException;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName : YoupyOss
 * @Description : 又拍云
 * @Author : Lang
 * @Date: 2020-03-14 12:00
 */
public class UpyunOss extends Oss{


    /**
     * 服务器名
     */
    private String bucket;

    /**
     * 操作员名
     */
    private String username;

    /**
     * 操作员密码
     */
    private String password;

    /**
     * 外链域名
     */
    private String domain;

    /**
     * 又拍云实例
     */
    private UpYun upyun;

    public UpyunOss(){}

    public UpyunOss(String username,String password,String bucket,String domain){
        this.username = username;
        this.password = password;
        this.bucket = bucket;
        //加上斜杠结尾方便统一拼接外链
        if(!Objects.isNull(domain)&&!domain.endsWith(File.separator)){
            domain = domain+File.separator;
        }
        this.domain = domain;
        this.upyun = getUpYunManager();
    }


    @Override
    public String upload(File targetFile) {
        return this.upload(targetFile,targetFile.getName());
    }

    @Override
    public String upload(File targetFile, String resourcesName) {
        try {
            upyun.writeFile(resourcesName, targetFile,true);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UpException e) {
            e.printStackTrace();
        }
        return domain+resourcesName;
    }

    @Override
    public String upload(String targetName, String resourcesName) {
        try {
            upyun.writeFile(resourcesName, targetName,true);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UpException e) {
            e.printStackTrace();
        }
        return domain+resourcesName;
    }

    @Override
    public String upload(byte[] data, String resourcesName) {
        try {
            upyun.writeFile(resourcesName, data,true);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UpException e) {
            e.printStackTrace();
        }
        return domain+resourcesName;
    }

    /**
     * @description 获取又拍云实例
     * @date 2020-03-14 13:42
     */
    private UpYun getUpYunManager(){
        // 创建实例
        UpYun upyun = new UpYun(this.bucket,this.username, this.password);
        // 可选属性1，是否开启 debug 模式，默认不开启
        upyun.setDebug(false);
        // 可选属性2，超时时间，默认 30s
        upyun.setTimeout(30);
        return  upyun;
    }
}
